﻿<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="chrome=1">
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
    <link rel="stylesheet" href="resources/ol.css" type="text/css">
    <link rel="stylesheet" href="resources/bootstrap/css/bootstrap.min.css" type="text/css">
    <link rel="stylesheet" href="resources/layout.css" type="text/css">
    <link rel="stylesheet" href="resources/bootstrap/css/bootstrap-responsive.min.css" type="text/css">
    <style type="text/css">
        .ol-popup {
            display: none;
            position: absolute;
            background-color: white;
            -moz-box-shadow: 0 1px 4px rgba(0,0,0,0.2);
            padding: 15px;
            border-radius: 10px;
            border: 1px solid #cccccc;
            bottom: 12px;
            left: -50px;
        }

            .ol-popup:after, .ol-popup:before {
                top: 100%;
                border: solid transparent;
                content: " ";
                height: 0;
                width: 0;
                position: absolute;
                pointer-events: none;
            }

            .ol-popup:after {
                border-top-color: white;
                border-width: 10px;
                left: 48px;
                margin-left: -10px;
            }

            .ol-popup:before {
                border-top-color: #cccccc;
                border-width: 11px;
                left: 48px;
                margin-left: -11px;
            }

        .ol-popup-closer {
            text-decoration: none;
            position: absolute;
            top: 2px;
            right: 8px;
        }

            .ol-popup-closer:after {
                content: "✖";
            }
    </style>
    <script type="text/javascript">
        // <![CDATA[

        function initSql() {
            $.ajax({
                type: "POST",
                url: "../WebService.asmx/InitMySql",
                data: "{}",
                contentType: "application/json",
                dataType: "json",
                async: true,
                success: function (result) {
                    alert(result.d);
                },
                error: function (err) {
                    alert("错误:" + err);
                }
            });
        }

        function getJsonData(sql) {
            var res;

            $.ajax({
                type: "POST",
                url: "../WebService.asmx/GetJsonData",
                data: "{sql: '" + sql + "'}",
                contentType: "application/json",
                dataType: "json",
                async: false,
                success: function (result) {
                    alert(result.d);
                    res = eval('(' + result.d + ')');
                },
                error: function (err) {
                    alert("错误：" + err);
                }
            });

            return res;
        }

        //设置为geojson文件后加载...
        function setGeoJson(sql) {
            var res;

            $.ajax({
                type: "POST",
                url: "../WebService.asmx/SetCellGeoJsonData",
                data: "{sql: '" + sql + "'}",
                contentType: "application/json",
                dataType: "json",
                async: false,
                success: function (result) {
                    //alert(result.d);
                    res = result.d;
                },
                error: function (err) {
                    //alert("错误：" + err);
                    res = "错误：" + err;
                }
            });

            alert("JSON数据:" + res);

            return res;
        }

        var openLayerMap = (function () {
            //地图实例
            var openmap = null;

            //地图div
            var mapElementId = "googlemap";

            //弹出窗体
            function initialPopup() {
                /**
                 * Elements that make up the popup.
                 */
                var container = document.getElementById('popup');
                var content = document.getElementById('popup-content');
                var closer = document.getElementById('popup-closer');

                /**
                 * Add a click handler to hide the popup.
                 * @return {boolean} Don't follow the href.
                 */
                closer.onclick = function () {
                    container.style.display = 'none';
                    closer.blur();
                    return false;
                };

                /**
                 * Create an overlay to anchor the popup to the map.
                 */
                var overlay = new ol.Overlay({
                    element: container
                });

                openmap.addOverlay(overlay);

                /**
                 * Add a click handler to the map to render the popup.
                 */
                openmap.on('click', function (evt) {


                    var coordinate = evt.coordinate;

                    var pixel = evt.pixel;

                    var feature = openmap.forEachFeatureAtPixel(pixel, function (feature, layer) {
                        return feature;
                    });

                    if (feature) {
                        var tempValue = feature.get('year') + '-' + feature.get('month') + ': ' + feature.get('name');
                        content.innerHTML = '<p>the values:</p><code>' + tempValue +
                        '</code>';
                    } else {

                        var hdms = ol.coordinate.toStringHDMS(ol.proj.transform(
                                coordinate, 'EPSG:3857', 'EPSG:4326'));
                        content.innerHTML = '<p>You clicked here:</p><code>' + hdms +
                        '</code>';
                    }

                    overlay.setPosition(coordinate);

                    container.style.display = 'block';

                });
            }

            //获取地图div
            function getMapElement() {
                return document.getElementById(mapElementId);
            };

            //显示地图
            function showMap() {
                if (!openmap) {
                    createMap();
                }
            };

            function initalDragMap() {
                //interactions: ol.interaction.defaults().extend([dragAndDropInteraction]),

                var defaultStyle = {
                    'Point': [new ol.style.Style({
                        image: new ol.style.Circle({
                            fill: new ol.style.Fill({
                                color: 'rgba(255,255,0,0.5)'
                            }),
                            radius: 5,
                            stroke: new ol.style.Stroke({
                                color: '#ff0',
                                width: 1
                            })
                        })
                    })],
                    'LineString': [new ol.style.Style({
                        stroke: new ol.style.Stroke({
                            color: '#f00',
                            width: 3
                        })
                    })],
                    'Polygon': [new ol.style.Style({
                        fill: new ol.style.Fill({
                            color: 'rgba(0,255,255,0.5)'
                        }),
                        stroke: new ol.style.Stroke({
                            color: '#0ff',
                            width: 1
                        })
                    })],
                    'MultiPoint': [new ol.style.Style({
                        image: new ol.style.Circle({
                            fill: new ol.style.Fill({
                                color: 'rgba(255,0,255,0.5)'
                            }),
                            radius: 5,
                            stroke: new ol.style.Stroke({
                                color: '#f0f',
                                width: 1
                            })
                        })
                    })],
                    'MultiLineString': [new ol.style.Style({
                        stroke: new ol.style.Stroke({
                            color: '#0f0',
                            width: 3
                        })
                    })],
                    'MultiPolygon': [new ol.style.Style({
                        fill: new ol.style.Fill({
                            color: 'rgba(0,0,255,0.5)'
                        }),
                        stroke: new ol.style.Stroke({
                            color: '#00f',
                            width: 1
                        })
                    })]
                };

                var styleFunction = function (feature, resolution) {
                    var featureStyleFunction = feature.getStyleFunction();
                    if (featureStyleFunction) {
                        return featureStyleFunction.call(feature, resolution);
                    } else {
                        return defaultStyle[feature.getGeometry().getType()];
                    }
                };

                var dragAndDropInteraction = new ol.interaction.DragAndDrop({
                    formatConstructors: [
                        ol.format.GPX,
                        ol.format.GeoJSON,
                        ol.format.IGC,
                        ol.format.KML,
                        ol.format.TopoJSON
                    ]
                });

                dragAndDropInteraction.on('addfeatures', function (event) {
                    var vectorSource = new ol.source.Vector({
                        features: event.features,
                        projection: event.projection
                    });
                    openmap.getLayers().push(new ol.layer.Vector({
                        source: vectorSource,
                        style: styleFunction
                    }));
                    var view = openmap.getView();
                    view.fitExtent(
                            vectorSource.getExtent(), /** @type {ol.Size} */ (openmap.getSize()));
                });
            };


            //创建地图
            function createMap() {
                if (typeof ol === "undefined") return;

                if (openmap)
                    openmap.Dispose();

                var mousePositionControl = new ol.control.MousePosition({
                    coordinateFormat: ol.coordinate.createStringXY(4),
                    projection: 'EPSG:4326',
                    //注释掉下面两行默认在地图内显示鼠标经过经纬度
                    /*      className: 'custom-mouse-position',
                     target: document.getElementById('info'),*/
                    undefinedHTML: '&nbsp;'
                });

                var layers = [
                    new ol.layer.Tile({
                        source: new ol.source.MapQuest({ layer: 'osm' })
                    })

                   /* new ol.layer.Tile({
                        source: new ol.source.TileWMS(({
                            url: 'http://10.141.132.183:50004/geoserver/wms',
                            params: { 'LAYERS': 'zhejiang', 'TILED': true },
                            serverType: 'geoserver'
                        }))
                    })*/
                ];

                openmap = new ol.Map({
                    controls: ol.control.defaults({
                        attributionOptions: /** @type {olx.control.AttributionOptions} */ ({
                            collapsible: true
                        })
                    }).extend([
                        new ol.control.ScaleLine(),
                        new ol.control.Rotate(),
                        new ol.control.ZoomSlider(),
                        mousePositionControl
                    ]),
                    target: mapElementId,
                    layers: layers,
                    view: new ol.View({
                        center: ol.proj.transform([121.3527, 31.1058], 'EPSG:4326', 'EPSG:3857'),
                        zoom: 9
                    })
                });
                resizeMap();

                //initialPopup();
            };

            //收起地图
            function collapseMap() {
                if (typeof ol === "undefined") return;
                //alert("Collapse");
                getMapElement().style.height = 0;
                getMapElement().style.width = 0;
            };

            //Resize窗体
            function resizeMap() {
                var mapElement = getMapElement();
                var mapElementParentNode = mapElement.parentNode.parentNode;
                mapElement.style.width = "100%";
                mapElement.style.height = mapElementParentNode.clientHeight + "px";
                openmap.width = mapElement.clientWidth;
                openmap.height = mapElementParentNode.clientHeight;
                openmap.updateSize();
            };

            function drawGeoJsonLayer() {

                // var jsonFile = setGeoJson("Select longitude as x,latitude as y,ArcPts as points,LAC,CI,BTS_NAME as name from dtdb_dezhou.cellinfo");

                // alert(jsonFile);

                /*     var image = new ol.style.Circle({
                         radius: 5,
                         fill: null,
                         stroke: new ol.style.Stroke({ color: 'red', width: 1 })
                     });*/

                var image = new ol.style.Icon(/** @type {olx.style.IconOptions} */({
                    anchor: [0.5, 46],
                    anchorXUnits: 'fraction',
                    anchorYUnits: 'pixels',
                    opacity: 0.75,
                    src: 'Images/1.gif'
                }));

                var styles = {
                    'Point': [new ol.style.Style({
                        image: image
                    })],
                    'LineString': [new ol.style.Style({
                        stroke: new ol.style.Stroke({
                            color: 'green',
                            width: 1
                        })
                    })],
                    'MultiLineString': [new ol.style.Style({
                        stroke: new ol.style.Stroke({
                            color: 'green',
                            width: 1
                        })
                    })],
                    'MultiPoint': [new ol.style.Style({
                        image: image
                    })],
                    'MultiPolygon': [new ol.style.Style({
                        stroke: new ol.style.Stroke({
                            color: 'yellow',
                            width: 1
                        }),
                        fill: new ol.style.Fill({
                            color: 'rgba(255, 255, 0, 0.1)'
                        })
                    })],
                    'Polygon': [new ol.style.Style({
                        stroke: new ol.style.Stroke({
                            color: 'blue',
                            lineDash: [4],
                            width: 3
                        }),
                        fill: new ol.style.Fill({
                            color: 'rgba(0, 0, 255, 0.1)'
                        })
                    })],
                    'GeometryCollection': [new ol.style.Style({
                        stroke: new ol.style.Stroke({
                            color: 'magenta',
                            width: 2
                        }),
                        fill: new ol.style.Fill({
                            color: 'magenta'
                        }),
                        image: new ol.style.Circle({
                            radius: 10,
                            fill: null,
                            stroke: new ol.style.Stroke({
                                color: 'magenta'
                            })
                        })
                    })],
                    'Circle': [new ol.style.Style({
                        stroke: new ol.style.Stroke({
                            color: 'red',
                            width: 2
                        }),
                        fill: new ol.style.Fill({
                            color: 'rgba(255,0,0,0.2)'
                        })
                    })]
                };

                var styleFunction = function (feature, resolution) {
                    var type = resolution < 5000 ? feature.getGeometry().getType() : '';
                    return styles[type];
                };

                var vectorSource = new ol.source.GeoJSON({
                    projection: 'EPSG:3857',
                    url: 'data/cell.geojson'
                });

                var jsonVector = new ol.layer.Vector({
                    source: vectorSource,
                    style: styleFunction
                });

                openmap.addLayer(jsonVector);
            };

            function initialLayerGroup() {

            };

            function drawPoints(json) {

                var count = json.length;

                var iconFeatures = new Array(count);

                $.each(json, function (idx, item) {

                    var iconFeature = new ol.Feature({
                        geometry: new ol.geom.Point(ol.proj.transform([Number(item.x), Number(item.y)], 'EPSG:4326', 'EPSG:3857')),
                        name: item.value,
                        year: item.year,
                        month: item.month
                    });

                    iconFeatures[idx] = iconFeature;
                });

                var vectorSource = new ol.source.Vector({
                    features: iconFeatures
                });

                var styleCache = {};
                var vectorLayer = new ol.layer.Vector({
                    source: vectorSource,
                    style: function (feature, resolution) {
                        var text = resolution < 5000 ? feature.get('name') : '';

                        if (!styleCache[text]) {
                            styleCache[text] = [
                                new ol.style.Style({
                                    image: new ol.style.Icon( /** @type {olx.style.IconOptions} */({
                                        anchor: [0.5, 46],
                                        anchorXUnits: 'fraction',
                                        anchorYUnits: 'pixels',
                                        opacity: 0.75,
                                        src: 'Images/weather.png'
                                    }))
                                })
                            ];
                        }
                        return styleCache[text];
                    }
                });

                openmap.addLayer(vectorLayer);
            };

            return {
                showMap: showMap,
                createMap: createMap,
                collapseMap: collapseMap,
                resizeMap: resizeMap,
                drawPoints: drawPoints,
                drawGeoJsonLayer: drawGeoJsonLayer,
                initialLayerGroup: initialLayerGroup
            };

        })();

        var openTreeView = (function () {
            function nodeClick(s, e) {
                var year = e.node.name;

                var json = getJsonData("Select x,y,year,month,value from webTest.Test where year = " + year);

                if (typeof json === "undefined") return;

                alert(year);

                openLayermap.drawPoints(json);

            };
            return {
                nodeClick: nodeClick
            };
        })();
        // ]]>
    </script>
    <title>MapTest</title>
</head>
<body onload="openLayerMap.createMap()">
    <input id="btnShowMap" type="button"
           style="width: 113px" value="加载基站" onclick="openLayerMap.drawGeoJsonLayer()">

    <input id="btnShowTree" type="button"
           style="width: 113px" value="邻区工具">

    <input id="btnShowChart" type="button"
           style="width: 113px" value="专题">

    <div class="container-fluid">
        <div id="googlemap" class="map"></div>
    </div>

    <div class="span6">
        <div id="info">&nbsp info;</div>
    </div>
    <script src="resources/ol.js" type="application/javascript"></script>
    <script src="resources/jquery-2.1.1.min.js" type="text/javascript"></script>
    <script src="resources/example-behaviour.js" type="text/javascript"></script>
</body>
</html>